package Login;

import java.io.IOException;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Utils.Constant;
import Utils.DbAccess;
import Utils.MD5;
import Utils.ZipResponse;

public class DoLogin extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		proccess(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		proccess(req, resp);
	}

	private void proccess(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/xml");
		String xml = "<root value='false'/>";
		String action = req.getParameter("act");

		DbAccess db = null;

		try {
			if (action.equals("login")) {
				String username = req.getParameter("username");
				String password = req.getParameter("password");

				db = new DbAccess();
				db.connectTemp("localhost", Constant.DB);
				String sql = "Select * from accounts where username=? and password=MD5(?)";
				db.stmt = db.conn.prepareStatement(sql);

				db.stmt.setString(1, username);
				db.stmt.setString(2, password);

				db.rs = db.stmt.executeQuery();
				if (db.rs.next()) {
					HttpSession session = req.getSession();
					xml = "<root value='true'/>";
					session.setAttribute("userid", username);
					session.setMaxInactiveInterval(60 * 360);
					db.stmt.close();
				}
			} else if (action.equals("checklogin")) {
				Object obj_userid = req.getSession().getAttribute("userid");
				if (obj_userid != null) {
					String uid = obj_userid.toString();
					xml = "<root value='true' uid='" + uid + "'/>";
				} else {
					xml = "<root value='false'/>";
				}
			}
		} catch (Exception e) {
			xml = "<root value='false'/>";
			e.printStackTrace();
		} finally {
			if (db != null)
				db.DBClose();
		}

		ZipResponse.write(req, res, xml, "UTF-8");

	}
}
